﻿<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>教务管理系统 - 请假审批</title>
    <link href="${pageContext.request.contextPath}/resources/bootstrap5/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons - 本地版本 -->
    <link href="${pageContext.request.contextPath}/resources/bootstrap-icons/1.11.3/bootstrap-icons.css" rel="stylesheet">
    <!-- Bootstrap Icons - 备用CDN -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-icons/1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
    <!-- 第二个备用CDN -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <style>
        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }

        .header {
            background-color: #1976d2;
            color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            position: fixed;
            width: 100%;
            top: 0;
            z-index: 1000;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .header h2 {
            margin: 0;
            font-size: 1.5rem;
            display: flex;
            align-items: center;
        }

        .header h2 img {
            height: 36px;
            margin-right: 10px;
        }

        .header .breadcrumb {
            margin: 0;
            background: transparent;
            color: white;
        }

        .header .breadcrumb a {
            color: rgba(255,255,255,0.8);
            text-decoration: none;
        }

        .header .breadcrumb a:hover {
            color: white;
        }

        .header .breadcrumb-item.active {
            color: white;
        }

        .header .breadcrumb-item+.breadcrumb-item::before {
            color: rgba(255,255,255,0.6);
        }

        /* 侧边栏样式 */
        .sidebar {
            position: fixed;
            top: 56px;
            left: 0;
            bottom: 0;
            width: 250px;
            background-color: white;
            box-shadow: 2px 0 5px rgba(0,0,0,0.1);
            overflow-y: auto;
            z-index: 100;
            padding-top: 20px;
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu > li {
            margin-bottom: 5px;
        }

        .sidebar-menu > li > a {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: #333;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }

        .sidebar-menu > li > a:hover {
            background-color: #f0f0f0;
            border-left-color: #1976d2;
        }

        .sidebar-menu > li > a.active {
            background-color: #e3f2fd;
            border-left-color: #1976d2;
            color: #1976d2;
        }

        .sidebar-menu > li > a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }

        .sidebar-submenu {
            list-style: none;
            padding-left: 53px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }

        .sidebar-menu > li.open .sidebar-submenu {
            max-height: 500px;
        }

        .sidebar-submenu > li > a {
            display: block;
            padding: 8px 0;
            color: #666;
            text-decoration: none;
            transition: all 0.3s;
        }

        .sidebar-submenu > li > a:hover {
            color: #1976d2;
        }

        .sidebar-submenu > li > a.active {
            color: #1976d2;
            font-weight: 500;
        }

        /* 内容区样式 */
        .content {
            margin-left: 250px;
            padding: 76px 20px 20px;
        }

        /* 用户名下拉菜单样式 */
        .header-user {
            display: flex;
            align-items: center;
            position: relative;
        }
        .header-user-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 8px;
            object-fit: cover;
            background: #fff;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .header-user-avatar:hover {
            transform: scale(1.1);
        }
        .header-user-name {
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            min-width: 160px;
            z-index: 1001;
            opacity: 0;
            visibility: hidden;
            transform: translateY(-10px);
            transition: all 0.3s ease;
            margin-top: 8px;
        }
        .user-dropdown.show {
            opacity: 1;
            visibility: visible;
            transform: translateY(0);
        }
        .user-dropdown::before {
            content: '';
            position: absolute;
            top: -6px;
            right: 20px;
            width: 12px;
            height: 12px;
            background: #fff;
            transform: rotate(45deg);
            box-shadow: -2px -2px 4px rgba(0,0,0,0.1);
        }
        .user-dropdown-item {
            display: flex;
            align-items: center;
            padding: 12px 16px;
            color: #333;
            text-decoration: none;
            transition: background 0.2s;
            border-bottom: 1px solid #f0f0f0;
            font-family: 'Microsoft YaHei', Arial, sans-serif;
        }
        .user-dropdown-item:last-child {
            border-bottom: none;
        }
        .user-dropdown-item:hover {
            background: #f8f9fa;
            color: #1976d2;
        }
        .user-dropdown-item i {
            margin-right: 8px;
            width: 16px;
            text-align: center;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            padding: 15px 20px;
            background-color: white;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-body {
            padding: 20px;
        }

        .search-bar {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 18px;
            flex-wrap: nowrap;
        }

        .search-bar input, .search-bar select {
            border-radius: 8px;
            border: 1px solid #e3e3e3;
            padding: 6px 14px;
            font-size: 1rem;
            flex: 1;
            min-width: 150px;
        }

        .search-bar .btn {
            border-radius: 8px;
            font-size: 1rem;
            padding: 6px 18px;
            font-weight: 500;
            box-shadow: none;
            flex-shrink: 0;
        }

        .btn-primary {
            background: #1976d2;
            border: none;
        }

        .btn-primary:hover {
            background: #1565c0;
        }

        .btn-warning {
            background: #ffb300;
            color: #fff;
            border: none;
        }

        .btn-warning:hover {
            background: #ff9800;
            color: #fff;
        }

        .btn-success {
            background: #4caf50;
            border: none;
        }

        .btn-success:hover {
            background: #388e3c;
        }

        .btn-danger {
            background: #f44336;
            border: none;
        }

        .btn-danger:hover {
            background: #d32f2f;
        }

        .btn-info {
            background: #03a9f4;
            border: none;
        }

        .btn-info:hover {
            background: #0288d1;
        }

        .table {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .table thead th {
            background: #f8f9fa;
            color: #1976d2;
            font-weight: bold;
            text-align: center;
            border-bottom: 2px solid #e3e3e3;
        }

        .table tbody tr {
            transition: background 0.2s;
        }

        .table tbody tr:hover {
            background: #f1f8ff;
        }

        .table td, .table th {
            vertical-align: middle !important;
            text-align: center;
        }

        .pagination {
            justify-content: center;
            margin-top: 12px;
        }

        .pagination .page-item .page-link {
            border-radius: 6px !important;
            margin: 0 2px;
            color: #1976d2;
            border: none;
            background: #fff;
            font-weight: 500;
            transition: background 0.2s, color 0.2s;
        }

        .pagination .page-item.active .page-link {
            background: #1976d2;
            color: #fff;
        }

        .pagination .page-item .page-link:hover {
            background: #e3f2fd;
            color: #1565c0;
        }

        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .content {
                margin-left: 0;
            }

            .search-bar {
                flex-wrap: wrap;
            }

            .search-bar input, .search-bar select {
                min-width: 100%;
                margin-bottom: 10px;
            }
        }
    </style>
</head>
<body>
<!-- 页头部分 -->
<div class="header">
    <div class="header-left">
        <h2><img src="${pageContext.request.contextPath}/resources/images/logo.png" alt="Logo"> 教务管理系统</h2>
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="${pageContext.request.contextPath}/teacher/home">教师首页</a></li>
                <li class="breadcrumb-item active">请假审批</li>
            </ol>
        </nav>
    </div>

    <!-- 用户名下拉菜单 -->
    <div class="header-user" id="userDropdownContainer">
        <img src="${pageContext.request.contextPath}/resources/images/baimao.png" class="header-user-avatar" alt="用户名头像" id="userAvatar">
        <span class="header-user-name" id="userName">
                <c:choose>
                    <c:when test="${not empty currentTeacher and not empty currentTeacher.user and not empty currentTeacher.user.realName}">
                        ${currentTeacher.user.realName}
                    </c:when>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.realName}">
                        ${sessionScope.loggedInUser.realName}
                    </c:when>
                    <c:when test="${not empty sessionScope.loggedInUser and not empty sessionScope.loggedInUser.username}">
                        ${sessionScope.loggedInUser.username}
                    </c:when>
                    <c:otherwise>
                        教学管理员
                    </c:otherwise>
                </c:choose>
            </span>
        <div class="user-dropdown" id="userDropdown">
            <a href="#" class="user-dropdown-item" onclick="showProfileModal()">
                <i class="bi bi-person-circle"></i>
                个人资料
            </a>
            <a href="${pageContext.request.contextPath}/teacher/changePassword" class="user-dropdown-item">
                <i class="bi bi-key"></i>
                修改密码
            </a>
            <a href="${pageContext.request.contextPath}/user/logout" class="user-dropdown-item">
                <i class="bi bi-box-arrow-right"></i>
                注销登录
            </a>
        </div>
    </div>
</div>

<!-- 侧边栏 -->
<div class="sidebar">
    <ul class="sidebar-menu">
        <li>
            <a href="${pageContext.request.contextPath}/teacher/home">
                <i class="bi bi-house-door"></i> 教师首页
            </a>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-megaphone"></i> 通知管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/academic">教学通知</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/exam">考试安排</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/notifications/classroom">教学环境安排</a></li>
            </ul>
        </li>
        <li>
            <a href="#" class="has-submenu">
                <i class="bi bi-book"></i> 教学管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/courses">我的课程</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/course-students">选课学生</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/homework">作业管理</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/grades">成绩管理</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/attendance">考勤管理</a></li>
            </ul>
        </li>
        <li class="open">
            <a href="#" class="has-submenu">
                <i class="bi bi-person-check"></i> 学生管理
            </a>
            <ul class="sidebar-submenu">
                <li><a href="${pageContext.request.contextPath}/teacher/evaluation">教学评价</a></li>
                <li><a href="${pageContext.request.contextPath}/teacher/leave" class="active">请假审批</a></li>
            </ul>
        </li>
        <li>
            <a href="${pageContext.request.contextPath}/user/logout">
                <i class="bi bi-box-arrow-right"></i> 注销登录
            </a>
        </li>
    </ul>
</div>

<!-- 内容区 -->
<div class="content">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">请假审批</h1>
    </div>

    <c:if test="${not empty error}">
        <div class="alert alert-danger" role="alert">
                ${error}
        </div>
    </c:if>

    <c:if test="${not empty success}">
        <div class="alert alert-success" role="alert">
                ${success}
        </div>
    </c:if>

    <!-- 查询部分 -->
    <div class="card">
        <div class="card-header">
            <span>请假审批查询</span>
        </div>
        <div class="card-body">
            <form method="get" action="${pageContext.request.contextPath}/teacher/leave">
                <div class="search-bar">
                    <select class="form-select" name="courseId">
                        <option value="">选择课程</option>
                        <c:forEach var="course" items="${teacherCourses}">
                            <option value="${course.id}" ${searchCourseId == course.id ? 'selected' : ''}>
                                    ${course.name}
                            </option>
                        </c:forEach>
                    </select>
                    <select class="form-select" name="statusSearch">
                        <option value="">选择状态</option>
                        <option value="0" ${statusSearch == 0 ? 'selected' : ''}>待审批</option>
                        <option value="1" ${statusSearch == 1 ? 'selected' : ''}>已批准</option>
                        <option value="2" ${statusSearch == 2 ? 'selected' : ''}>已拒绝</option>
                    </select>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i> 查询
                    </button>
                    <a href="${pageContext.request.contextPath}/teacher/leave" class="btn btn-warning">
                        <i class="bi bi-arrow-clockwise"></i> 重置
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- 请假申请列表 -->
    <div class="card">
        <div class="card-header">
            <span>学生请假申请</span>
        </div>
        <div class="card-body">
            <c:choose>
                <c:when test="${empty leaves}">
                    <div class="text-center py-5">
                        <i class="bi bi-calendar-x" style="font-size: 3rem; color: #ccc;"></i>
                        <p class="text-muted mt-3">暂无请假申请</p>
                    </div>
                </c:when>
                <c:otherwise>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                            <tr>
                                <th style="width: 8%;">序号</th>
                                <th style="width: 10%;">学生姓名</th>
                                <th style="width: 12%;">学号</th>
                                <th style="width: 12%;">课程</th>
                                <th style="width: 20%;">请假原因</th>
                                <th style="width: 10%;">开始时间</th>
                                <th style="width: 10%;">结束时间</th>
                                <th style="width: 8%;">状态</th>
                                <th style="width: 10%;">申请时间</th>
                                <th style="width: 10%;">操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <c:forEach var="leave" items="${leaves}" varStatus="status">
                                <tr>
                                    <td>${(currentPage - 1) * pageSize + status.index + 1}</td>
                                    <td>${leave.student.user.realName}</td>
                                    <td>${leave.student.studentNo}</td>
                                    <td>${leave.course.name}</td>
                                    <td>
                                        <div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${leave.reason}">
                                                ${leave.reason}
                                        </div>
                                    </td>
                                    <td>${leave.startTime}</td>
                                    <td>${leave.endTime}</td>
                                    <td>
                                        <c:choose>
                                            <c:when test="${leave.status == 0}">
                                                <span class="badge bg-warning">待审批</span>
                                            </c:when>
                                            <c:when test="${leave.status == 1}">
                                                <span class="badge bg-success">已批准</span>
                                            </c:when>
                                            <c:when test="${leave.status == 2}">
                                                <span class="badge bg-danger">已拒绝</span>
                                            </c:when>
                                            <c:otherwise>
                                                <span class="badge bg-secondary">未知状态</span>
                                            </c:otherwise>
                                        </c:choose>
                                    </td>
                                    <td>${leave.createTime}</td>
                                    <td>
                                        <div class="d-flex gap-1 align-items-center">
                                            <button class="btn btn-sm btn-info" onclick="viewLeaveDetail(${leave.id})" title="查看详情">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                            <c:if test="${leave.status == 0}">
                                                <button class="btn btn-sm btn-success" onclick="approveLeave(${leave.id}, 1)" title="同意请假">
                                                    <i class="bi bi-check-lg"></i> 同意
                                                </button>
                                                <button class="btn btn-sm btn-danger" onclick="approveLeave(${leave.id}, 2)" title="拒绝请假">
                                                    <i class="bi bi-x-lg"></i> 拒绝
                                                </button>
                                            </c:if>
                                            <c:if test="${leave.status != 0}">
                                                <div class="d-flex gap-1 align-items-center">
                                                    <select class="form-select form-select-sm" id="modify_${leave.id}" style="width: 80px; font-size: 12px;" title="修改审批状态">
                                                        <option value="1" ${leave.status == 1 ? 'selected' : ''}>批准</option>
                                                        <option value="2" ${leave.status == 2 ? 'selected' : ''}>拒绝</option>
                                                    </select>
                                                    <button class="btn btn-sm btn-warning" onclick="modifyApproval(${leave.id})" title="修改审批">
                                                        <i class="bi bi-pencil-square"></i>
                                                    </button>
                                                </div>
                                            </c:if>
                                        </div>
                                    </td>
                                </tr>
                            </c:forEach>
                            </tbody>
                        </table>
                    </div>
                </c:otherwise>
            </c:choose>

            <!-- 分页 -->
            <c:if test="${totalPages != null && totalPages > 1}">
                <nav aria-label="请假记录分页">
                    <ul class="pagination justify-content-center">
                        <!-- 上一页 -->
                        <c:if test="${currentPage > 1}">
                            <li class="page-item">
                                <a class="page-link" href="?page=${currentPage - 1}&courseId=${searchCourseId}&statusSearch=${statusSearch}">上一页</a>
                            </li>
                        </c:if>


                        <!-- 页码 -->
                        <c:forEach begin="1" end="${totalPages}" var="i">
                            <li class="page-item ${i == currentPage ? 'active' : ''}">
                                <a class="page-link" href="?page=${i}&courseId=${searchCourseId}&statusSearch=${statusSearch}">${i}</a>
                            </li>
                        </c:forEach>



                        <!-- 下一页 -->
                        <c:if test="${currentPage < totalPages}">
                            <li class="page-item">
                                <a class="page-link" href="?page=${currentPage + 1}&courseId=${searchCourseId}&statusSearch=${statusSearch}">下一页</a>
                            </li>
                        </c:if>
                    </ul>
                </nav>
            </c:if>
        </div>
    </div>
</div>

<!-- 请假详情模态框 -->
<div class="modal fade" id="leaveDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">请假申请详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="leaveDetailContent">
                    <!-- 请假详情内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script src="${pageContext.request.contextPath}/resources/bootstrap5/js/bootstrap.bundle.min.js"></script>
<script>
    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 用户名下拉菜单操作
        const userDropdownContainer = document.getElementById('userDropdownContainer');
        const userDropdown = document.getElementById('userDropdown');

        if (userDropdownContainer && userDropdown) {
            userDropdownContainer.addEventListener('click', function(e) {
                e.stopPropagation();
                userDropdown.classList.toggle('show');
            });

            document.addEventListener('click', function() {
                userDropdown.classList.remove('show');
            });
        }

        // 侧边栏折叠菜单操作
        document.querySelectorAll('.has-submenu').forEach(function(item) {
            item.addEventListener('click', function(e) {
                e.preventDefault();
                this.parentNode.classList.toggle('open');
            });
        });
    });

    // 查看个人资料
    function showProfileModal() {
        // 关闭用户名下拉菜单
        const dropdown = document.getElementById('userDropdown');
        dropdown.classList.remove('show');

        // 弹出个人资料模态框
        alert('个人资料功能暂未实现');
    }

    // 查看请假详情
    function viewLeaveDetail(leaveId) {
        fetch('${pageContext.request.contextPath}/teacher/leave/view/' + leaveId)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const leave = data.leave;
                    const content = '<div class="row">' +
                        '<div class="col-md-6">' +
                        '<h6>请假信息</h6>' +
                        '<p><strong>学生姓名：</strong>' + leave.student.user.realName + '</p>' +
                        '<p><strong>学号：</strong>' + leave.student.studentNo + '</p>' +
                        '<p><strong>课程：</strong>' + leave.course.name + '</p>' +
                        '<p><strong>申请时间：</strong>' + leave.createTime + '</p>' +
                        '</div>' +
                        '<div class="col-md-6">' +
                        '<h6>请假详情</h6>' +
                        '<p><strong>开始时间：</strong>' + leave.startTime + '</p>' +
                        '<p><strong>结束时间：</strong>' + leave.endTime + '</p>' +
                        '<p><strong>请假天数：</strong>' + (leave.leaveDays || '暂无信息') + ' 天</p>' +
                        '<p><strong>审批状态：</strong>' +
                        '<span class="badge ' + (leave.status == 0 ? 'bg-warning' : leave.status == 1 ? 'bg-success' : 'bg-danger') + '">' +
                        leave.statusText +
                        '</span>' +
                        '</p>' +
                        '</div>' +
                        '</div>' +
                        '<div class="row mt-3">' +
                        '<div class="col-12">' +
                        '<h6>请假原因</h6>' +
                        '<div class="bg-light p-3 rounded">' + leave.reason + '</div>' +
                        '</div>' +
                        '</div>';
                    document.getElementById('leaveDetailContent').innerHTML = content;
                    new bootstrap.Modal(document.getElementById('leaveDetailModal')).show();
                } else {
                    alert('获取请假详情失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('获取请假详情失败');
            });
    }

    // 批准请假申请
    function approveLeave(leaveId, status) {
        const statusText = status == 1 ? '批准' : '拒绝';
        const statusColor = status == 1 ? 'success' : 'danger';
        const statusIcon = status == 1 ? 'check-circle' : 'x-circle';

        // 显示Bootstrap确认模态框
        showConfirmModal(
            '确认操作',
            '您确定要将请假申请标记为<strong class="text-' + statusColor + '">' + statusText + '</strong>吗？<br><br>' +
            '<small class="text-muted">此操作将更新请假状态，请谨慎操作。</small>',
            '确认' + statusText,
            statusColor,
            function() {
                performApproval(leaveId, status, statusText);
            }
        );
    }

    // 执行请假审批
    function performApproval(leaveId, status, statusText) {
        // 显示加载状态
        const button = document.querySelector('button[onclick="approveLeave(' + leaveId + ', ' + status + ')"]');
        const originalHtml = button.innerHTML;
        button.disabled = true;
        button.innerHTML = '<i class="bi bi-hourglass-split"></i>';

        // 禁用当前行的所有按钮
        const row = button.closest('tr');
        const allButtons = row.querySelectorAll('button[onclick*="approveLeave"]');
        allButtons.forEach(btn => btn.disabled = true);

        const formData = new FormData();
        formData.append('leaveId', leaveId);
        formData.append('status', status);

        fetch('${pageContext.request.contextPath}/teacher/leave/approve', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功提示
                    showSuccessToast(data.message);

                    // 更新行状态
                    updateRowStatus(leaveId, status);
                } else {
                    // 显示错误提示
                    showErrorToast('审批失败: ' + data.message);

                    // 恢复按钮状态
                    button.disabled = false;
                    button.innerHTML = originalHtml;
                    allButtons.forEach(btn => btn.disabled = false);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showErrorToast('审批请求失败，请稍后重试');

                // 恢复按钮状态
                button.disabled = false;
                button.innerHTML = originalHtml;
                allButtons.forEach(btn => btn.disabled = false);
            });
    }

    // 更新行状态
    function updateRowStatus(leaveId, status) {
        const row = document.querySelector('button[onclick="viewLeaveDetail(' + leaveId + ')"]').closest('tr');
        const statusCell = row.cells[7]; // 状态单元格
        const actionCell = row.cells[9]; // 操作单元格
        // 更新状态显示
        if (status == 1) {
            statusCell.innerHTML = '<span class="badge bg-success">已批准</span>';
        } else if (status == 2) {
            statusCell.innerHTML = '<span class="badge bg-danger">已拒绝</span>';
        }

        // 更新操作单元格
        actionCell.innerHTML =
            '<div class="d-flex gap-1">' +
            '<button class="btn btn-sm btn-info" onclick="viewLeaveDetail(' + leaveId + ')">' +
            '<i class="bi bi-eye"></i>' +
            '</button>' +
            '<span class="text-muted small">已处理</span>' +
            '</div>';

        // 闪烁背景
        row.style.backgroundColor = '#d4edda';
        setTimeout(() => {
            row.style.backgroundColor = '';
        }, 2000);
    }

    // 显示确认模态框
    function showConfirmModal(title, message, confirmText, confirmColor, onConfirm) {
        const modalHtml =
            '<div class="modal fade" id="confirmModal" tabindex="-1">' +
            '<div class="modal-dialog">' +
            '<div class="modal-content">' +
            '<div class="modal-header">' +
            '<h5 class="modal-title">' +
            '<i class="bi bi-question-circle text-warning me-2"></i>' + title +
            '</h5>' +
            '<button type="button" class="btn-close" data-bs-dismiss="modal"></button>' +
            '</div>' +
            '<div class="modal-body">' +
            message +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>' +
            '<button type="button" class="btn btn-' + confirmColor + '" id="confirmButton">' +
            '<i class="bi bi-check-lg me-1"></i>' + confirmText +
            '</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

        // 删除旧的模态框
        const oldModal = document.getElementById('confirmModal');
        if (oldModal) {
            oldModal.remove();
        }

        // 添加新的模态框
        document.body.insertAdjacentHTML('beforeend', modalHtml);

        const modal = new bootstrap.Modal(document.getElementById('confirmModal'));

        // 确认按钮点击事件
        document.getElementById('confirmButton').addEventListener('click', function() {
            modal.hide();
            onConfirm();
        });

        modal.show();

        // 模态框关闭时移除
        document.getElementById('confirmModal').addEventListener('hidden.bs.modal', function() {
            this.remove();
        });
    }

    // 显示成功提示
    function showSuccessToast(message) {
        showToast(message, 'success', 'bi-check-circle');
    }

    // 显示错误提示
    function showErrorToast(message) {
        showToast(message, 'danger', 'bi-exclamation-triangle');
    }

    // 显示Toast提示
    function showToast(message, type, icon) {
        const toastHtml =
            '<div class="toast align-items-center text-white bg-' + type + ' border-0" role="alert" style="position: fixed; top: 20px; right: 20px; z-index: 9999;">' +
            '<div class="d-flex">' +
            '<div class="toast-body">' +
            '<i class="bi ' + icon + ' me-2"></i>' + message +
            '</div>' +
            '<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>' +
            '</div>' +
            '</div>';

        document.body.insertAdjacentHTML('beforeend', toastHtml);
        const toastElement = document.body.lastElementChild;
        const toast = new bootstrap.Toast(toastElement, { delay: 3000 });

        toast.show();

        // Toast关闭时移除
        toastElement.addEventListener('hidden.bs.toast', function() {
            this.remove();
        });
    }

    // 修改请假审批状态
    function modifyApproval(leaveId) {
        const selectElement = document.getElementById('modify_' + leaveId);

        // 检查选择器是否存在
        if (!selectElement) {
            showErrorToast('未找到对应的审批状态选择器，请刷新页面');
            return;
        }

        const newStatus = parseInt(selectElement.value);
        const currentStatus = selectElement.querySelector('option[selected]') ?
            parseInt(selectElement.querySelector('option[selected]').value) :
            (selectElement.selectedIndex === 0 ? 1 : 2);

        // 如果新状态与当前状态相同，则提示用户
        if (newStatus === currentStatus) {
            showErrorToast('新状态与当前状态相同，请选择不同的状态');
            return;
        }

        const statusText = newStatus == 1 ? '批准' : '拒绝';
        const statusColor = newStatus == 1 ? 'success' : 'danger';
        const currentStatusText = currentStatus == 1 ? '批准' : '拒绝';

        // 显示确认修改模态框
        showConfirmModal(
            '确认修改审批状态',
            '您确定要将审批状态从<strong class="text-' + (currentStatus == 1 ? 'success' : 'danger') + '">' + currentStatusText + '</strong>' +
            '修改为<strong class="text-' + statusColor + '">' + statusText + '</strong>吗？<br><br>' +
            '<small class="text-muted">此操作将更新请假状态，请谨慎操作。</small>',
            '确认修改',
            'warning',
            function() {
                performModifyApproval(leaveId, newStatus, statusText);
            }
        );
    }

    // 执行修改请假审批状态
    function performModifyApproval(leaveId, newStatus, statusText) {
        const button = document.querySelector('button[onclick="modifyApproval(' + leaveId + ')"]');
        const selectElement = document.getElementById('modify_' + leaveId);

        // 检查按钮和选择器是否存在
        if (!button || !selectElement) {
            showErrorToast('未找到对应的按钮或选择器，请刷新页面');
            return;
        }

        // 显示加载状态
        const originalHtml = button.innerHTML;
        button.disabled = true;
        selectElement.disabled = true;
        button.innerHTML = '<i class="bi bi-hourglass-split"></i>';

        const formData = new FormData();
        formData.append('leaveId', leaveId);
        formData.append('status', newStatus);

        fetch('${pageContext.request.contextPath}/teacher/leave/approve', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 显示成功提示
                    showSuccessToast('审批状态已更新为: ' + statusText);

                    // 更新行状态
                    updateRowStatusForModify(leaveId, newStatus);
                } else {
                    // 显示错误提示
                    showErrorToast('修改审批状态失败: ' + data.message);

                    // 恢复按钮和选择器状态
                    button.disabled = false;
                    selectElement.disabled = false;
                    button.innerHTML = originalHtml;

                    // 恢复选择器的当前状态
                    selectElement.selectedIndex = newStatus == 1 ? 1 : 0;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showErrorToast('修改审批状态请求失败，请稍后重试');

                // 恢复按钮和选择器状态
                button.disabled = false;
                selectElement.disabled = false;
                button.innerHTML = originalHtml;

                // 恢复选择器的当前状态
                selectElement.selectedIndex = newStatus == 1 ? 1 : 0;
            });
    }

    // 更新行状态（修改审批状态）
    function updateRowStatusForModify(leaveId, status) {
        const row = document.querySelector('button[onclick="viewLeaveDetail(' + leaveId + ')"]').closest('tr');
        const statusCell = row.cells[7]; // 状态单元格
        const selectElement = document.getElementById('modify_' + leaveId);
        const button = document.querySelector('button[onclick="modifyApproval(' + leaveId + ')"]');

        // 检查元素是否存在
        if (!row || !statusCell || !selectElement || !button) {
            console.warn('未找到对应的 DOM 元素');
            return;
        }

        // 更新状态显示
        if (status == 1) {
            statusCell.innerHTML = '<span class="badge bg-success">已批准</span>';
        } else if (status == 2) {
            statusCell.innerHTML = '<span class="badge bg-danger">已拒绝</span>';
        }

        // 更新选择器的选中状态
        selectElement.value = status;
        selectElement.querySelector('option[selected]')?.removeAttribute('selected');
        const targetOption = selectElement.querySelector('option[value="' + status + '"]');
        if (targetOption) {
            targetOption.setAttribute('selected', 'selected');
        }

        // 恢复按钮和选择器状态
        button.disabled = false;
        selectElement.disabled = false;
        button.innerHTML = '<i class="bi bi-pencil-square"></i>';

        // 闪烁背景
        row.style.backgroundColor = '#fff3cd'; // 淡黄色闪烁背景表示修改成功
        setTimeout(() => {
            row.style.backgroundColor = '';
        }, 2000);
    }
</script>
</body>
</html>

